package com.example.usercenter.sys.web;

import com.alibaba.fastjson.JSONObject;
import com.example.usercenter.common.utils.FreemarkerUtil;
import com.example.usercenter.common.utils.JdbcUtil;
import com.example.usercenter.common.base.Page;
import com.example.usercenter.common.base.ResponseData;
import com.example.usercenter.common.utils.ZipUtils;
import com.example.usercenter.config.GenCodeTemplateConfig;
import com.example.usercenter.sys.entity.GenCodeTemplate;
import com.example.usercenter.sys.entity.TableModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;
import java.util.zip.ZipOutputStream;

/**
 * Created by ZXN on 2018/9/19.
 */
@Controller
@RequestMapping( value = "genCode" )
public class GenCodeController {
    @Autowired
    private JdbcUtil jdbcUtil;
    @Autowired
    private GenCodeTemplateConfig config;

    /**
     * 获取数据库表列表
     * */
    @RequestMapping( value = "page")
    @ResponseBody
    @PreAuthorize("hasAuthority('GEN_CODE')")
    public ResponseData getTables(@RequestBody JSONObject params){
        List<TableModel> tables = jdbcUtil.getTables();
        String tableName = params.getString("tableName");
        if(!StringUtils.isEmpty(tableName)){
            tables = tables.stream().filter(item -> {
               return item.getTableName().indexOf(tableName) >= 0;
            }).collect(Collectors.toList());
        }
        return ResponseData.ok("获取数据库表列表成功", new Page(tables, tables.size()));
    }

    /**
     * 根据表名获取数据库表结构
     * */
    @RequestMapping( value = "/{tableName}")
    @ResponseBody
    @PreAuthorize("hasAuthority('GEN_CODE')")
    public ResponseData getTable(@PathVariable("tableName") String tableName){
        TableModel table = jdbcUtil.getTableStructure(tableName);
        return ResponseData.ok("获取数据库表结构成功", table);
    }

    @GetMapping( value = "/download")
    @PreAuthorize("hasAuthority('GEN_CODE')")
    public void download(HttpServletRequest request, HttpServletResponse response){
        TableModel table = jdbcUtil.getTableStructure(request.getParameter("tableName"));
        GenCodeTemplate template = new GenCodeTemplate(table, config);
        String path = request.getServletContext().getRealPath("/") + "/temp/";
        File floder = new File(path);
        if (floder.exists()) {
            File[] subFiles = floder.listFiles();
            if(subFiles!=null && subFiles.length>0){
                for(File f : subFiles){
                    f.delete();
                }
            }
            floder.delete();
        }
        floder.mkdir();
        try {
            FreemarkerUtil.genTemplate("mybatis.xml", template, new FileOutputStream(new File(floder.getPath() + "/" + JdbcUtil.toFirstCharLowerCase(template.getEntityClass().getClassName()) + ".xml")));
            FreemarkerUtil.genTemplate("Dao.java", template, new FileOutputStream(new File(floder.getPath() + "/" + template.getDaoClass().getClassName() + ".java")));
            FreemarkerUtil.genTemplate("Service.java", template, new FileOutputStream(new File(floder.getPath() + "/" + template.getServiceClass().getClassName() + ".java")));
            FreemarkerUtil.genTemplate("Controller.java", template, new FileOutputStream(new File(floder.getPath() + "/" + template.getControllerClass().getClassName() + ".java")));
            FreemarkerUtil.genTemplate("Entity.java", template, new FileOutputStream(new File(floder.getPath() + "/" + template.getEntityClass().getClassName() + ".java")));
            FreemarkerUtil.genTemplate("table.vue", template, new FileOutputStream(new File(floder.getPath() + "/table.vue")));
            FreemarkerUtil.genTemplate("add.vue", template, new FileOutputStream(new File(floder.getPath() + "/add.vue")));
            FreemarkerUtil.genTemplate("update.vue", template, new FileOutputStream(new File(floder.getPath() + "/update.vue")));
            FreemarkerUtil.genTemplate("detail.vue", template, new FileOutputStream(new File(floder.getPath() + "/detail.vue")));
            FreemarkerUtil.genTemplate("zh.js", template, new FileOutputStream(new File(floder.getPath() + "/zh.js")));
            FreemarkerUtil.genTemplate("en.js", template, new FileOutputStream(new File(floder.getPath() + "/en.js")));
            String filename = new String(template.getTableName().getBytes("gb2312" ), "ISO8859-1");
            response.setHeader("Content-disposition", "attachment; filename="+ filename+".zip");
            response.setContentType("application/octet-stream");
            //创建zip输出流
            ZipOutputStream out = new ZipOutputStream(response.getOutputStream());
            File[] files = floder.listFiles();
            for(File f : files){
                ZipUtils.doCompress(f, out);
                response.flushBuffer();
            }
            out.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
